<template>
  <div class="dmt-container">
    <div class="dmt-selector">
      <el-radio-group v-model="activeDmtDevice" size="small" @change="handleDeviceChange">
        <el-radio-button label="AIMMS-30" value="AIMMS-30">AIMMS-30</el-radio-button>
        <el-radio-button label="CDP" value="CDP">CDP</el-radio-button>
        <el-radio-button label="CIP" value="CIP">CIP</el-radio-button>
        <el-radio-button label="PIP" value="PIP">PIP</el-radio-button>
        <el-radio-button label="LWC" value="LWC">LWC-100</el-radio-button>
        <el-radio-button label="PCASP" value="PCASP">PCASP</el-radio-button>
        <el-radio-button label="CCN" value="CCN">CCN-100</el-radio-button>
        <el-radio-button label="FCDP" value="FCDP">FCDP</el-radio-button>
      </el-radio-group>
    </div>

    <div class="dmt-charts-container" v-loading="loading">
      <template v-if="activeDmtDevice === 'AIMMS-30'">
        <div class="dmt-chart-item" v-for="(item, index) in aimmsChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'CDP'">
        <div class="dmt-chart-item" v-for="(item, index) in cdpChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'CIP'">
        <div class="dmt-chart-item" v-for="(item, index) in cipChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'PIP'">
        <div class="dmt-chart-item" v-for="(item, index) in pipChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'LWC'">
        <div class="dmt-chart-item" v-for="(item, index) in lwcChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'PCASP'">
        <div class="dmt-chart-item" v-for="(item, index) in pcaspChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'CCN'">
        <div class="dmt-chart-item" v-for="(item, index) in ccnChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'FCDP'">
        <div class="dmt-chart-item" v-for="(item, index) in fcdpChartItems" :key="index">
          <div class="chart-title">{{ item.title }}</div>
          <div :ref="el => { if (el) chartRefs[item.ref] = el }" class="echarts-chart"></div>
        </div>
      </template>

      <template v-else>
        <div class="empty-charts">
          <el-empty description="该设备的图表数据即将接入" />
        </div>
      </template>
    </div>

    <!-- DMT数据摘要 -->
    <div class="data-summary">
      <template v-if="activeDmtDevice === 'AIMMS-30'">
        <div class="summary-item" v-for="(item, index) in aimmsSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'CDP'">
        <div class="summary-item" v-for="(item, index) in cdpSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'CIP'">
        <div class="summary-item" v-for="(item, index) in cipSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'PIP'">
        <div class="summary-item" v-for="(item, index) in pipSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'LWC'">
        <div class="summary-item" v-for="(item, index) in lwcSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'PCASP'">
        <div class="summary-item" v-for="(item, index) in pcaspSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'CCN'">
        <div class="summary-item" v-for="(item, index) in ccnSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>

      <template v-else-if="activeDmtDevice === 'FCDP'">
        <div class="summary-item" v-for="(item, index) in fcdpSummaryItems" :key="index">
          <div class="item-title">{{ item.title }}</div>
          <div class="item-value">{{ dmtSensorData[item.field] || '--' }} {{ item.unit }}</div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart, BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent,
  ToolboxComponent,
  MarkLineComponent
} from 'echarts/components';
import { getHistoryProbe } from '@/api/aircraft';
import { CanvasRenderer } from 'echarts/renderers';
import { ElMessage } from 'element-plus';
import useInfoDataStore from "@/stores/modules/infoData";


const infoData = useInfoDataStore();
// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent,
  LineChart,
  BarChart,
  CanvasRenderer,
  ToolboxComponent,
  MarkLineComponent
]);

const props = defineProps({
  active: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:dmtData']);

// 机载探测 设备类型
const activeDmtDevice = ref('AIMMS-30');

// SSE事件源
let eventSource = null;

// 图表实例
const chartInstances = ref({});
const chartRefs = ref({});

// 图表项配置
const aimmsChartItems = ref([
  { title: 'T_温度 (°C)', ref: 'temperature', field: 'T_温度', color: '#ff9f40', unit: '°C' },
  { title: 'RH_相对湿度 (%)', ref: 'humidity', field: 'RH_湿度', color: '#4bc0c0', unit: '%' },
  { title: 'P_气压 (mBar)', ref: 'pressure', field: 'P_气压', color: '#6154e5', unit: 'hPa' }
]);

const cdpChartItems = ref([
  { title: '直径 (um)', ref: 'cdpDiameter', field: 'CDP_直径', color: '#36a2eb', unit: 'um' },
  { title: '浓度 (#/cm³)', ref: 'cdpConc', field: 'CDP_浓度', color: '#ff6384', unit: '#/cm³' },
  { title: 'LWC (g/m³)', ref: 'cdpLWC', field: 'CDP_LWC', color: '#ffcd56', unit: 'g/m³' }
]);

const cipChartItems = ref([
  { title: '直径 (um)', ref: 'cipDiameter', field: 'CIP_直径', color: '#36a2eb', unit: 'um' },
  { title: '浓度 (#/cm³)', ref: 'cipConc', field: 'CIP_浓度', color: '#ff6384', unit: '#/cm³' },
  { title: 'LWC (g/cm³)', ref: 'cipLWC', field: 'CIP_LWC', color: '#ffcd56', unit: 'g/cm³' }
]);

const pipChartItems = ref([
  { title: '直径 (um)', ref: 'pipDiameter', field: 'PIP_diameter', color: '#36a2eb', unit: 'um' },
  { title: '浓度 (#/cm³)', ref: 'pipConc', field: 'PIP_conc', color: '#ff6384', unit: '#/cm³' },
  { title: 'LWC (g/cm³)', ref: 'pipLWC', field: 'PIP_LWC', color: '#ffcd56', unit: 'g/cm³' }
]);

const lwcChartItems = ref([
  { title: 'LWC_calc (g/m³)', ref: 'lwcCalc', field: 'LWC_calc', color: '#36a2eb', unit: 'g/m³' },
  { title: 'LWC_Obs (g/m³)', ref: 'lwcObs', field: 'LWC_Obs', color: '#ff6384', unit: 'g/m³' }
]);

const pcaspChartItems = ref([
  { title: '直径 (um)', ref: 'pcaspDiameter', field: 'PCASP_diameter', color: '#36a2eb', unit: 'um' },
  { title: '浓度 (#/cm³)', ref: 'pcaspConc', field: 'PCASP_conc', color: '#ff6384', unit: '#/cm³' }
]);

const ccnChartItems = ref([
  { title: '浓度 (#/cm³)', ref: 'ccnConc', field: 'CCN_conc', color: '#36a2eb', unit: '#/cm³' },
  { title: '过饱和度', ref: 'ccnSS', field: 'CCN_SS', color: '#ff6384', unit: '' }
]);

const fcdpChartItems = ref([
  { title: '大气湿度 (%)', ref: 'fcdpRH', field: 'FCDP_RH', color: '#36a2eb', unit: '%' },
  { title: '大气压力 (hPa)', ref: 'fcdpPressure', field: 'FCDP_pressure', color: '#ff6384', unit: 'hPa' }
]);

// 摘要项配置
const aimmsSummaryItems = ref([
  { title: '温度', field: 'T_温度', unit: '°C' },
  { title: '相对湿度', field: 'RH_湿度', unit: '%' },
  { title: '气压', field: 'P_气压', unit: 'hPa' }
]);

const cdpSummaryItems = ref([
  { title: '直径', field: 'CDP_直径', unit: 'um' },
  { title: '浓度', field: 'CDP_浓度', unit: '#/cm³' },
  { title: 'LWC', field: 'CDP_LWC', unit: 'g/m³' }
]);

const cipSummaryItems = ref([
  { title: '直径', field: 'CIP_直径', unit: 'um' },
  { title: '浓度', field: 'CIP_浓度', unit: '#/cm³' },
  { title: 'LWC', field: 'CIP_LWC', unit: 'g/cm³' }
]);

const pipSummaryItems = ref([
  { title: '直径', field: 'PIP_diameter', unit: 'um' },
  { title: '浓度', field: 'PIP_conc', unit: '#/cm³' },
  { title: 'LWC', field: 'PIP_LWC', unit: 'g/cm³' }
]);

const lwcSummaryItems = ref([
  { title: 'LWC_calc', field: 'LWC_calc', unit: 'g/m³' },
  { title: 'LWC_Obs', field: 'LWC_Obs', unit: 'g/m³' }
]);

const pcaspSummaryItems = ref([
  { title: '直径', field: 'PCASP_diameter', unit: 'um' },
  { title: '浓度', field: 'PCASP_conc', unit: '#/cm³' }
]);

const ccnSummaryItems = ref([
  { title: '浓度', field: 'CCN_conc', unit: '#/cm³' },
  { title: '过饱和度', field: 'CCN_SS', unit: '' }
]);

const fcdpSummaryItems = ref([
  { title: '大气湿度', field: 'FCDP_RH', unit: '%' },
  { title: '大气压力', field: 'FCDP_pressure', unit: 'hPa' }
]);

// DMT探测仪器数据
const dmtSensorData = ref({
  // AIMMS数据
  T_temperature: '', // 温度 -50~50℃
  RH_humidity: '',   // 相对湿度 0~100%
  P_pressure: '',    // 气压 200-1100hpa

  // CDP数据
  CDP_diameter: '',  // 直径 0-55um
  CDP_conc: '',      // 浓度 0-5000 #/cm³
  CDP_LWC: '',       // LWC 0-10 g/m³

  // CIP数据
  CIP_diameter: '',  // 直径 25-1550um
  CIP_conc: '',      // 浓度 0-3000 #/cm³
  CIP_LWC: '',       // LWC 0-10 g/cm³

  // PIP数据
  PIP_diameter: '',  // 直径 50-6500um
  PIP_conc: '',      // 浓度 0-2000 #/cm³
  PIP_LWC: '',       // LWC 0-30 g/cm³

  // LWC-100数据
  LWC_calc: '',      // LWC_calc 0-5 g/m³
  LWC_Obs: '',       // LWC_Obs 0-5 g/m³

  // PCASP数据
  PCASP_diameter: '', // 直径 0-3um
  PCASP_conc: '',     // 浓度 0-8000 #/cm³

  // CCN-100数据
  CCN_conc: '',       // 浓度 0-8000
  CCN_SS: '',         // 过饱和度

  // FCDP数据
  FCDP_RH: '',        // 大气湿度 0-100%
  FCDP_pressure: '',   // 大气压力 200-1100hpa

  updateTime: ''
});

// DMT历史数据
const dmtHistoryData = ref({
  'AIMMS-30': {
    time: [],
    T_温度: [],
    RH_湿度: [],
    P_气压: []
  },
  CDP: {
    time: [],
    CDP_直径: [],
    CDP_浓度: [],
    CDP_LWC: []
  },
  CIP: {
    time: [],
    CIP_直径: [],
    CIP_浓度: [],
    CIP_LWC: []
  },
  PIP: {
    time: [],
    PIP_diameter: [],
    PIP_conc: [],
    PIP_LWC: []
  },
  LWC: {
    time: [],
    LWC_calc: [],
    LWC_Obs: []
  },
  PCASP: {
    time: [],
    PCASP_diameter: [],
    PCASP_conc: []
  },
  CCN: {
    time: [],
    CCN_conc: [],
    CCN_SS: []
  },
  FCDP: {
    time: [],
    FCDP_RH: [],
    FCDP_pressure: []
  }
});

// 加载状态
const loading = ref(false);

// 计算属性：检查是否有可用数据
const noDataAvailable = computed(() => {
  if (!dmtHistoryData.value[activeDmtDevice.value]) {
    return true;
  }

  const deviceData = dmtHistoryData.value[activeDmtDevice.value];

  // 检查时间数组是否为空
  if (!deviceData.time || deviceData.time.length === 0) {
    return true;
  }

  // 根据不同设备检查关键数据
  switch (activeDmtDevice.value) {
    case 'AIMMS-30':
      return !deviceData['T_温度'] || deviceData['T_温度'].length === 0;
    case 'CDP':
      return !deviceData['CDP_直径'] || deviceData['CDP_直径'].length === 0;
    case 'CIP':
      return !deviceData['CIP_直径'] || deviceData['CIP_直径'].length === 0;
    case 'PIP':
      return !deviceData['PIP_diameter'] || deviceData['PIP_diameter'].length === 0;
    case 'LWC':
      return !deviceData['LWC_calc'] || deviceData['LWC_calc'].length === 0;
    case 'PCASP':
      return !deviceData['PCASP_diameter'] || deviceData['PCASP_diameter'].length === 0;
    case 'CCN':
      return !deviceData['CCN_conc'] || deviceData['CCN_conc'].length === 0;
    case 'FCDP':
      return !deviceData['FCDP_RH'] || deviceData['FCDP_RH'].length === 0;
    default:
      return true;
  }
});

// 处理窗口大小变化
const handleResize = () => {
  Object.values(chartInstances.value).forEach(chart => {
    if (chart) {
      chart.resize();
    }
  });
};

// 处理设备切换
const handleDeviceChange = () => {
  closeEventSource();
  initDmtCharts();
  getDmtData();
};

// 关闭EventSource连接
const closeEventSource = () => {
  if (eventSource) {
    eventSource.close();
    eventSource = null;
  }
};

// 获取dmt数据
const getDmtData = async () => {
  if (!infoData.flightInfo.id) {
    ElMessage.warning('获取DMT数据失败: 缺少飞行编号');
    return;
  }
  if (infoData.currentMode == 'history') {
    let result = await getHistoryProbe({
      fn: infoData.flightInfo.id,
      type: activeDmtDevice.value
    });
    console.log(result);

    if (result) {
      parseAndUpdateDmtData(result[0]);
    } else {
      ElMessage.error(`获取DMT数据失败`);
    }
    return false;
  }

  try {
    closeEventSource();
    loading.value = true;

    const apiUrl = `${import.meta.env.VITE_WEB_BASE_API}/probe/realtime/sse?fn=${infoData.flightInfo.id}&type=${activeDmtDevice.value}`;

    eventSource = new EventSource(apiUrl);

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data && data.length > 0) {
          parseAndUpdateDmtData(data[0]);
        }
        loading.value = false;

      } catch (error) {
        console.error("解析DMT数据失败:", error, event.data);
        ElMessage.error(`解析DMT数据失败: ${error.message}`);
      }
    };

    eventSource.onerror = (error) => {
      console.error("DMT数据连接错误:", error);
      ElMessage.error(`DMT数据连接错误: ${error.type}`);
      loading.value = false;
      closeEventSource();
    };

    eventSource.onopen = () => {
      // console.log("DMT数据连接已建立");
    };
  } catch (error) {
    loading.value = false;
    ElMessage.error(`获取DMT数据失败: ${error.message}`);
    console.error("获取DMT数据失败:", error);
  }
};

// 解析和更新DMT数据
const parseAndUpdateDmtData = (data) => {
  if (!data || !data[activeDmtDevice.value]) return;

  const deviceData = data[activeDmtDevice.value];
  const now = new Date().toLocaleTimeString('zh-CN', { hour12: false });

  const newSensorData = { ...dmtSensorData.value, updateTime: now };

  if (!dmtHistoryData.value[activeDmtDevice.value]) {
    dmtHistoryData.value[activeDmtDevice.value] = {
      time: []
    };
  }

  let currentTime = now;
  if (deviceData.length > 0 && deviceData[0].time) {
    currentTime = deviceData[0].time;
  }

  const lastTimePoint = dmtHistoryData.value[activeDmtDevice.value].time[dmtHistoryData.value[activeDmtDevice.value].time.length - 1];
  if (!lastTimePoint || lastTimePoint !== currentTime) {
    dmtHistoryData.value[activeDmtDevice.value].time.push(currentTime);

    if (dmtHistoryData.value[activeDmtDevice.value].time.length > 50) {
      dmtHistoryData.value[activeDmtDevice.value].time.shift();
    }
  }

  // 处理每个数据项
  deviceData.forEach(item => {
    if (!item.label || item.value === undefined) return;

    // 更新当前传感器数据
    newSensorData[item.label] = parseFloat(item.value) || item.value;

    // 更新历史数据
    if (!dmtHistoryData.value[activeDmtDevice.value][item.label]) {
      dmtHistoryData.value[activeDmtDevice.value][item.label] = Array(dmtHistoryData.value[activeDmtDevice.value].time.length - 1).fill(null);
      dmtHistoryData.value[activeDmtDevice.value][item.label].push(parseFloat(item.value) || 0);
    } else {
      if (lastTimePoint !== currentTime) {
        dmtHistoryData.value[activeDmtDevice.value][item.label].push(parseFloat(item.value) || 0);

        if (dmtHistoryData.value[activeDmtDevice.value][item.label].length > 50) {
          dmtHistoryData.value[activeDmtDevice.value][item.label].shift();
        }
      } else {
        const lastIndex = dmtHistoryData.value[activeDmtDevice.value][item.label].length - 1;
        if (lastIndex >= 0) {
          dmtHistoryData.value[activeDmtDevice.value][item.label][lastIndex] = parseFloat(item.value) || 0;
        }
      }
    }
  });

  // 更新传感器数据
  dmtSensorData.value = newSensorData;

  // 向父组件发送更新事件
  emit('update:dmtData', dmtSensorData.value);

  // 更新图表
  updateDmtChartData();
};

// 初始化DMT图表
const initDmtCharts = () => {
  Object.values(chartInstances.value).forEach(chart => {
    if (chart) {
      chart.dispose();
    }
  });

  chartInstances.value = {};

  nextTick(() => {
    let chartItems;
    switch (activeDmtDevice.value) {
      case 'AIMMS-30':
        chartItems = aimmsChartItems.value;
        break;
      case 'CDP':
        chartItems = cdpChartItems.value;
        break;
      case 'CIP':
        chartItems = cipChartItems.value;
        break;
      case 'PIP':
        chartItems = pipChartItems.value;
        break;
      case 'LWC':
        chartItems = lwcChartItems.value;
        break;
      case 'PCASP':
        chartItems = pcaspChartItems.value;
        break;
      case 'CCN':
        chartItems = ccnChartItems.value;
        break;
      case 'FCDP':
        chartItems = fcdpChartItems.value;
        break;
      default:
        return;
    }

    initDeviceCharts(chartItems);
  });
};

// 初始化设备图表
const initDeviceCharts = (chartItems) => {
  if (!dmtHistoryData.value[activeDmtDevice.value]) {
    dmtHistoryData.value[activeDmtDevice.value] = {
      time: []
    };
  }

  chartItems.forEach(item => {
    const el = chartRefs.value[item.ref];
    if (el) {
      const chart = echarts.init(el);

      const timeData = dmtHistoryData.value[activeDmtDevice.value].time || [];

      if (!dmtHistoryData.value[activeDmtDevice.value][item.field]) {
        dmtHistoryData.value[activeDmtDevice.value][item.field] = [];
      }

      const valueData = dmtHistoryData.value[activeDmtDevice.value][item.field] || [];

      const option = createChartOption(
        item.title,
        timeData,
        valueData,
        item.color,
        item.unit
      );

      // 设置图表选项
      chart.setOption(option);

      // 保存图表实例
      chartInstances.value[item.ref] = chart;
    }
  });
};

// 创建图表选项
const createChartOption = (name, xData, yData, color, unit) => {
  return {
    backgroundColor: '#fff',
    animation: false,
    animationDuration: 0,
    animationDurationUpdate: 0,
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const param = params[0];
        if (param.value === null || param.value === undefined) {
          return `${param.axisValue}<br/>${param.marker} ${param.seriesName}: 无数据`;
        }
        return `${param.axisValue}<br/>${param.marker} ${param.seriesName}: ${param.value} ${unit}`;
      }
    },
    grid: {
      left: '3%',
      right: '3%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666',
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: color,
          width: 1.5
        }
      },
      axisLabel: {
        color: color,
        fontSize: 10
      },
      splitLine: {
        lineStyle: {
          color: '#eee',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: name,
        type: 'line',
        data: yData,
        symbol: 'circle',
        symbolSize: 5,
        showSymbol: false, // 不显示所有数据点的图形标记
        smooth: true,
        connectNulls: true,
        lineStyle: {
          color: color,
          width: 2
        },
        itemStyle: {
          color: color,
          borderWidth: 2,
          borderColor: '#fff'
        },
        emphasis: {
          // 鼠标划过时才显示图形标记
          itemStyle: {
            borderWidth: 2,
            borderColor: '#fff'
          },
          scale: true
        }
      }
    ]
  };
};

// 更新图表数据
const updateDmtChartData = () => {
  let chartItems;

  switch (activeDmtDevice.value) {
    case 'AIMMS-30':
      chartItems = aimmsChartItems.value;
      break;
    case 'CDP':
      chartItems = cdpChartItems.value;
      break;
    case 'CIP':
      chartItems = cipChartItems.value;
      break;
    case 'PIP':
      chartItems = pipChartItems.value;
      break;
    case 'LWC':
      chartItems = lwcChartItems.value;
      break;
    case 'PCASP':
      chartItems = pcaspChartItems.value;
      break;
    case 'CCN':
      chartItems = ccnChartItems.value;
      break;
    case 'FCDP':
      chartItems = fcdpChartItems.value;
      break;
    default:
      return;
  }

  // 确保设备数据存在
  if (!dmtHistoryData.value[activeDmtDevice.value]) {
    return;
  }

  chartItems.forEach(item => {
    const chart = chartInstances.value[item.ref];
    if (!chart) return;

    // 获取时间和数据数组
    const timeData = dmtHistoryData.value[activeDmtDevice.value].time || [];
    const valueData = dmtHistoryData.value[activeDmtDevice.value][item.field] || [];

    // 更新图表数据
    chart.setOption({
      xAxis: {
        data: timeData
      },
      series: [{
        data: valueData
      }]
    });
  });
};

// 刷新DMT数据
const refreshDmtData = () => {
  if (!props.active) return;
  getDmtData();
};

// 组件挂载时初始化
onMounted(() => {
  window.addEventListener('resize', handleResize);

  // 初始化图表
  initDmtCharts();

  // 如果激活且有飞行编号，获取数据
  if (props.active && infoData.flightInfo.id) {
    getDmtData();
  }
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  closeEventSource();
});

// 监听活动状态变化
watch(() => props.active, (newVal) => {
  if (newVal && infoData.flightInfo.id) {
    getDmtData();
  } else if (!newVal) {
    closeEventSource();
  }
});

// 监听飞行编号变化
watch(() => infoData.flightInfo.id, (newVal) => {
  if (newVal && props.active) {
    getDmtData();
  }
});

defineExpose({
  refreshDmtData,
  closeEventSource
});
</script>

<style lang="scss" scoped>
.dmt-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;

  .dmt-selector {
    padding: 12px 15px;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: center;
  }

  .dmt-charts-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    padding: 10px;
    background-color: #f9f9f9;
    position: relative;

    .dmt-chart-item {
      background: #fff;
      border-radius: 8px;
      margin-bottom: 12px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      height: 180px;
      overflow: hidden;

      .chart-title {
        padding: 8px 10px;
        font-size: 13px;
        color: #606266;
        background-color: #f7f9fc;
        border-bottom: 1px solid #ebeef5;
        font-weight: 500;
      }

      .echarts-chart {
        height: calc(100% - 33px);
        width: 100%;
      }
    }

    .empty-charts {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 300px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    }
  }

  .data-summary {
    padding: 10px 15px;
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    background-color: #f9f9f9;
    border-top: 1px solid #eee;

    .summary-item {
      background-color: #fff;
      border-radius: 6px;
      padding: 12px;
      min-width: 100px;
      flex: 1;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      transition: all 0.2s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }

      .item-title {
        font-size: 12px;
        color: #666;
        margin-bottom: 6px;
      }

      .item-value {
        font-size: 16px;
        color: #333;
        font-weight: 500;
      }
    }
  }
}
</style>